#include <math.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>
#include <arpa/inet.h>

#include "Constant.h"
#include "Beacon.h"

int beacon_counter;
int overhead_num;
int overhead_byte;

void beacon_init()
{
	beacon_counter = 300;
	overhead_byte = overhead_num = 0;
	printf("beacon_init\n");
}

void* calculateOverhead(void *null)
{
	while(1)
	{
		sleep(60);
		printf("\n------------------Overhead------------------\n");
		printf("beacon num:%d\tbyte:%0.2fKB\n\n", overhead_num, overhead_byte / 1024.0);
		overhead_byte = overhead_num = 0;
	}
	return (void *)NULL;
}

void* beacon(void *null)
{
	char packet[MAX_PACKET_LEN];
	int len;
	int sockfd;

	if((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
	{
		perror("D_broadcast---socket.");
		printf("errno:%d\n", errno);
		exit(1);
	}

	int so_broadcast = 1;
	setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, &so_broadcast, sizeof(so_broadcast));

	struct sockaddr_in broadcast_addr;
	bzero(&broadcast_addr, sizeof(broadcast_addr));
	broadcast_addr.sin_family = AF_INET;
	broadcast_addr.sin_port = htons(BROADCASTPORT);
	if(inet_aton(BROADCASTIP, &broadcast_addr.sin_addr)<0)
	{
		perror("beacon---inet_aton.");
		printf("errno:%d\n", errno);
		exit(1);
	}

	packet[0]=0x01;
	while(1)
	{
		--beacon_counter;
		usleep(0.5*1000000+rand()%1000000);//average 1.0s

		if(beacon_counter<=0)
		{
			len = getTableInfo(packet+1) + 1;
			if(sendto(sockfd, packet, len, 0, (struct sockaddr *)&broadcast_addr, sizeof(broadcast_addr))<0)
			{
				perror("beacon--sendto.");
				printf("errno:%d\n", errno);
			}
			else
			{
				printf("send a beacon\n");
				overhead_byte += len;
				++overhead_num;
			}

			beacon_counter = 300;
		}
	}
	return (void *)NULL;
}

void set_beacon_counter(int a)
{
	printf("set_beacon_counter: %d\n", a);
	beacon_counter = a;
}


